<script setup>
import { onMounted, ref } from 'vue'
import dial from './dial.vue'
import { getAllApi, updateApi } from '@/api/warehousingentry/warehousingEntryDetails'
import { addBatchApi } from '@/api/warehousingentry/warehousingEntryDetailsSort'
import { ElMessage } from 'element-plus'
import eventBus from '@/utils/eventBus'

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref('default')
const background = ref(true)
const disabled = ref(false)

const handleSizeChange = (val) => {
  pageSize.value = val
  getAll()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getAll()
}

const form = ref({
  skuId: null,
  warehousingEntryId: null
})

const getAll = async () => {
  let res = await getAllApi(
    currentPage.value,
    pageSize.value
  )
  total.value = res.total
  tableData.value = res.rows
}

const diaRef = ref(null)
const search = () => {
  currentPage.value = 1
  getAll()
}

const ids = ref([])
const handleSelectionChange = (val) => {
  ids.value = val.map(item => item.id)
}

const confirmEntry = async () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  const res = await updateApi(ids.value.map(id => ({
    id,
    status: 3
  })))

  if (res.code) {
    // 获取选中的记录详情
    const selectedRows = tableData.value.filter(row => ids.value.includes(row.id))

    // 构造分拣管理数据
    const sortDataList = selectedRows.map(row => ({
      warehousingEntryDetailsId: row.id,  // 对应入库明细ID
      skuId: row.skuId,                   // 规格ID
      count: row.count,                   // 分拣数量
      status: 1,                          // 初始状态为"分拣中"
      damageCount: 0,                     // 初始破损数量为0
      surpassCount: 0,                    // 初始超出数量为0
      lackCount: 0                        // 初始缺少数量为0
    }))

    // 批量插入分拣管理数据
    const sortRes = await addBatchApi(sortDataList)

    if (sortRes.code) {
      ElMessage.success('入库确认成功，并已转交分拣管理！')
      // 发送刷新事件
      eventBus.emit('refreshSortPage')
    } else {
      ElMessage.warning('入库确认成功，但转交分拣管理失败！')
    }

    getAll()
  } else {
    ElMessage.error('确认失败')
  }
}
const getItemNameById = (skuId) => {
  if (!diaRef.value || !diaRef.value.itemInfo) {
    return '未知商品'
  }
  for (const item of diaRef.value.itemInfo) {
    if (item.id === skuId) {
      return item.title
    }
  }
  return '未知商品'
}
const getItemInfoById = (skuId) => {
  if (!diaRef.value || !diaRef.value.itemInfo) {
    return '未知商品'
  }
  for (const item of diaRef.value.itemInfo) {
    if (item.id === skuId) {
      return item.subtitle
    }
  }
  return '未知商品'
}


defineExpose({
  refreshData: getAll
})

onMounted(() => {
  getAll()
  eventBus.on('refreshunloadPage', getAll)
})
</script>

<template>
  <dial ref="diaRef" @refresh="getAll" />
  <div>
    <el-button @click="confirmEntry" type="primary" style="float: left;">确认入库</el-button>
  </div>
  <el-form :model="form" :inline="true" style="float: right;">
    <el-form-item>
      <el-input v-model="form.skuId" placeholder="规格ID" />
    </el-form-item>
    <el-form-item>
      <el-input v-model="form.warehousingEntryId" placeholder="入库单ID" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column property="skuId" label="规格ID" />
    <el-table-column property="skuId" label="商品名称">
      <template #default="{ row }">
        {{ getItemNameById(row.skuId) }}
      </template>
    </el-table-column>
    <el-table-column property="skuId" label="规格名称">
      <template #default="{ row }">
        {{ getItemInfoById(row.skuId) }}
      </template>
    </el-table-column>
    <el-table-column property="count" label="数量" />
    <el-table-column property="supplierId" label="供应商ID" />
    <el-table-column property="price" label="单价(分)" />
    <el-table-column property="warehousingEntryId" label="入库单ID" />
    <el-table-column property="createTime" label="创建时间" />
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>